<!--
  ~ Copyright (c) 2024 Huawei Device Co., Ltd.
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
  <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
  />
  <title>活动详情 - H5页面B</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    html {
      /* 设置根字体大小，针对高分辨率设备调整 */
      font-size: 16px;
      font-size: max(16px, min(4vw, 24px));
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      min-height: 100vh;
      line-height: 1.6;
    }

    .container {
      width: 100%;
      background: white;
      padding: 1rem;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .title {
      height: 3.5rem;
      display: flex;
      font-weight: 700;
      text-align: center;
      line-height: 3.5rem;
      font-size: 1.875rem;
    }

    .title-back {
      width: 2.5rem;
      height: 2.5rem;
      border-radius: 50%;
      background-color: #e6e8e9;
      margin-top: 0.5rem;
      margin-right: 0.5rem;
      line-height: 2.375rem;
    }

    .section-margin {
      margin-top: 1.125rem;
    }

    .sub-title {
      font-size: 1.125rem;
      font-weight: 700;
      margin-bottom: 0.625rem;
    }

    .content-container {
      height: 8.375rem;
      border-radius: 1rem;
      padding: 1rem 0;
      background-color: #e6e8e9;
    }

    .content-text {
      width: 100%;
      max-height: 6.375rem;
      font-size: 1rem;
      padding: 0 1rem;
      overflow-y: auto;
      word-break: break-all;
    }

    .description .description-content {
      font-size: 1rem;
      color: rgba(0, 0, 0, 0.6);
    }

    .button {
      width: 100%;
      height: 2.5rem;
      border-radius: 1.25rem;
      font-size: 1em;
      text-align: center;
      line-height: 2.5rem;
      margin-top: 0.75rem;
      color: #fff;
      background-color: #0a59f7;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="top">
    <div class="title">
      <div class="title-text">活动详情</div>
    </div>

    <div class="description section-margin">
      <div class="sub-title">演示内容</div>
      <div class="description-content">
        <span>这是H5页面B，演示H5页面间的跳转</span><br />
        <span>协议URL：h5://event/detail</span><br />
      </div>
    </div>

    <div class="params-info section-margin">
      <div class="sub-title">页面参数</div>
      <div class="content-container">
        <div id="params" class="content-text">等待加载...</div>
      </div>
    </div>

    <div class="log section-margin">
      <div class="sub-title">日志展示区</div>
      <div class="content-container">
        <div id="log" class="content-text">等待加载...</div>
      </div>
    </div>
  </div>

  <div class="button-group">
    <div class="button" onclick="goToNativePageA()">跳转到ArkUI页面A</div>
    <div class="button" onclick="goBackToCart()">返回购物车 (H5页面A)</div>
    <div class="button" onclick="goBack()">返回上一页</div>
  </div>

<script>
  let logContainer = document.getElementById('log');

  // 日志记录函数
  function addLog(message, type = 'info') {
    const time = new Date().toLocaleTimeString();
    const logElement = document.createElement('div');
    logElement.className = 'log-entry';

    let icon = '📝';
    switch (type) {
      case 'success':
        icon = '✅';
        break;
      case 'error':
        icon = '❌';
        break;
      case 'warning':
        icon = '⚠️';
        break;
      case 'route':
        icon = '🧭';
        break;
    }

    logElement.innerHTML = `
              <span class='log-time'>[${time}]</span>
              <span class='log-message'>${icon} ${message}</span>
          `;
    logContainer.appendChild(logElement);
    logContainer.scrollTop = logContainer.scrollHeight;
  }

  // 等待HMRouter Bridge准备就绪
  window.onHMRouterReady = function (params) {
    document.getElementById('params').textContent = JSON.stringify(params, null, 2);
    addLog('HMRouter Bridge 已准备就绪', 'success');
    addLog(`接收到页面参数: ${JSON.stringify(params)}`, 'info');

    // 如果是从购物车页面跳转过来的，显示特殊信息
    if (params.from === 'cart') {
      addLog('检测到从购物车页面跳转过来', 'route');
      if (params.recommendedItems) {
        addLog(`推荐商品: ${params.recommendedItems.join(', ')}`, 'info');
      }
    }

    console.log('🎉 H5页面B已加载，参数：', params);
  };

  // 监听Bridge对象准备就绪事件（立即通知）
  window.addEventListener('hmrouterbridgeready', function (event) {
    addLog('🚀 Bridge对象已创建，可以使用！', 'success');
    console.log('🚀 Bridge立即准备就绪事件:', event.detail);
  });

  // 跳转到ArkUI页面A
  function goToNativePageA() {
    if (window.HMRouterBridge) {
      const params = {
        from: 'h5_activity',
        activityId: 'double11_2024',
        selectedProduct: 'hmrouter_course',
        timestamp: Date.now(),
      };
      addLog(`准备跳转到ArkUI页面A，参数: ${JSON.stringify(params)}`, 'route');
      window.HMRouterBridge.push('NativePageA', params);
    } else {
      addLog('HMRouter Bridge 未准备就绪', 'error');
      alert('HMRouter Bridge 未准备就绪，请稍后再试');
    }
  }

  // 返回到购物车页面
  function goBackToCart() {
    if (window.HMRouterBridge) {
      const params = {
        from: 'event_detail',
        selectedActivity: 'double11_2024',
        addToCart: true,
      };
      addLog(`准备返回购物车页面，参数: ${JSON.stringify(params)}`, 'route');
      window.HMRouterBridge.push('h5://shopping/cart', params);
    } else {
      addLog('HMRouter Bridge 未准备就绪', 'error');
      alert('HMRouter Bridge 未准备就绪，请稍后再试');
    }
  }

  // 返回上一页
  function goBack() {
    if (window.HMRouterBridge) {
      addLog('准备返回上一页', 'route');
      window.HMRouterBridge.pop();
    } else {
      addLog('HMRouter Bridge 未准备就绪', 'error');
      alert('HMRouter Bridge 未准备就绪，请稍后再试');
    }
  }

  // 显示路由信息
  function showRouterInfo() {
    if (window.HMRouterBridge) {
      const params = window.HMRouterBridge.getParams();
      addLog('当前路由信息查询', 'route');
      addLog(`参数详情: ${JSON.stringify(params, null, 2)}`, 'info');

      // 弹窗显示详细信息
      const info = `
                  当前页面：H5活动详情页
                  协议URL：h5://event/detail
                  容器类型：WebView容器
                  参数数量：${Object.keys(params).length}

                  参数详情：
                  ${JSON.stringify(params, null, 2)}
              `;
      alert(info);
    } else {
      addLog('HMRouter Bridge 未准备就绪', 'error');
    }
  }

  // 模拟用户行为
  function simulateUserInteraction() {
    addLog('模拟用户浏览行为', 'info');

    setTimeout(() => {
      addLog('用户查看了商品详情', 'info');
    }, 2000);

    setTimeout(() => {
      addLog('用户滚动到了页面底部', 'info');
    }, 4000);
  }

  // 页面生命周期事件
  document.addEventListener('DOMContentLoaded', function () {
    addLog('DOM内容加载完成', 'success');
    simulateUserInteraction();
  });

  window.addEventListener('load', function () {
    addLog('页面完全加载完成', 'success');
  });

  // 页面可见性改变
  document.addEventListener('visibilitychange', function () {
    if (document.visibilityState === 'visible') {
      addLog('页面变为可见状态', 'info');
    } else {
      addLog('页面变为隐藏状态', 'warning');
    }
  });

  // 监听页面滚动
  let scrollTimer = null;
  window.addEventListener('scroll', function () {
    if (scrollTimer) { clearTimeout(scrollTimer) }
    scrollTimer = setTimeout(() => {
      const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
      if (scrollPercent > 50) {
        addLog(`用户已浏览${scrollPercent}%的内容`, 'info');
      }
    }, 500);
  });

  // 错误处理
  window.addEventListener('error', function (e) {
    addLog(`JavaScript错误: ${e.message}`, 'error');
    console.error('JavaScript错误:', e);
  });

  // 页面初始化
  addLog('🚀 活动详情页面开始初始化', 'success');
  addLog('等待HMRouter Bridge连接...', 'info');

  // 检查Bridge状态（改进的重试机制）
  let bridgeCheckCount = 0;
  const maxBridgeChecks = 16; // 最多检查16次（8秒）

  function checkBridgeStatus() {
    bridgeCheckCount++;

    if (window.HMRouterBridge) {
      addLog('✅ Bridge连接成功！', 'success');
      return;
    }

    if (bridgeCheckCount < maxBridgeChecks) {
      addLog(`🔍 Bridge连接检查 (${bridgeCheckCount}/${maxBridgeChecks})`, 'info');
      setTimeout(checkBridgeStatus, 500);
    } else {
      addLog('⚠️ Bridge连接超时，请检查容器状态', 'warning');
      addLog('💡 提示：您仍可以尝试点击按钮，Bridge可能在稍后准备就绪', 'info');
    }
  }

  // 500ms后开始检查
  setTimeout(checkBridgeStatus, 500);
</script>
</body>
</html>
